package com.softer.wxzj.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.softer.wxzj.common.entity.ActionResult;
import com.softer.wxzj.common.entity.CommonResult;
import com.softer.wxzj.common.enums.FileTypeEnum;
import com.softer.wxzj.common.enums.NumStrEnum;
import com.softer.wxzj.common.enums.NumberEnum;
import com.softer.wxzj.common.enums.ShiroResultEnum;
import com.softer.wxzj.common.error.CourseException;
import com.softer.wxzj.common.util.*;
import com.softer.wxzj.entity.*;
import com.softer.wxzj.mapper.BaseModifyDetailMapper;
import com.softer.wxzj.mapper.BaseModifyReqMapper;
import com.softer.wxzj.mapper.FileMapper;
import com.softer.wxzj.service.AccTransactionLogService;
import com.softer.wxzj.service.FileService;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Gong Zhiyang
 * @date 2018/10/10
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {
    /**
     * 服务器路径没有bin,linux下是"/",windows下是"\"
     */
    private static final String FILE_PATH = "./file";
    private static final String POINT = ".";
    private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss_SSS");
    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private BaseModifyDetailMapper baseModifyDetailMapper;
    @Autowired
    private BaseModifyReqMapper baseModifyReqMapper;
    @Autowired
    private ModifyUtil<FileServiceImpl> modifyUtil;
    @Value("${fileUrl}")
    private String fileUrl;
    @Value("${address}")
    private String address;
    @Autowired
    private AccTransactionLogService accTransactionLogService;

    /**
     * 删除附件
     *
     * @param id 附件ID
     * @return 删除结果
     */
    @Override
    public CommonResult delete(String id) {

        int num = fileMapper.delete(id);
        return CommonResult.ResponseResult(num);
    }

    /**
     * 上传附件
     *
     * @param file       附件
     * @param fileUpload 上传信息
     * @return 结果
     */
    @Override
    public CommonResult upload(MultipartFile file, FileUpload fileUpload) {
        Map<String, String> map = new HashMap<>(3);
        map.put("fileType", fileUpload.getFileType());
        String response = HttpUtils.uploadFile(address + fileUrl, file, map);
        ActionResult actionResult = JSONObject.parseObject(response, ActionResult.class);
        JSONObject data = (JSONObject) actionResult.getData();
        return JSONObject.parseObject(data.toJSONString(), CommonResult.class);
//        try {
//            //文件名
//            String fileName = file.getOriginalFilename();
//            fileUpload.setFileName(fileName);
//            if (StringUtils.isBlank(fileName)) {
//                return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "上传附件不存在");
//            }
//            //获取后缀
//            String suffix = fileName.substring(fileName.lastIndexOf(POINT));
//            fileName = LocalDateTime.now().format(formatter) + suffix;
//            //文件路径
//            StringBuffer filePath = new StringBuffer(10);
//            filePath.append(FILE_PATH).append("/").append(fileUpload.getFileType());
//            File targetFile = new File(filePath.toString());
//            if (!targetFile.exists()) {
//                targetFile.mkdirs();
//            }
//            //查询当前路径下的文件集合
//            ArrayList<String> fileList = getFile(filePath.toString());
//            //创建符合要求的文件名
//            fileName = checkFileName(fileList, fileName, NumberEnum.ZERO.getNum());
//            uploadFileUtil(file, filePath.toString(), fileName);
//            String path = filePath.append("/").append(fileName).toString().substring(1);
//            return CommonResult.idResult(NumberEnum.ONE.getNum(), path);
//        } catch (Exception e) {
//            log.error("上传文件错误", e);
//        }
//        return CommonResult.ResponseResult(NumberEnum.ZERO.getNum());
    }

    /**
     * 保存到数据库
     *
     * @param fileList 附件信息
     * @param id       业务编号
     * @return 新增结果
     */
    public CommonResult addFile(List<FileVO> fileList, String id) {
        if (fileList != null && !fileList.isEmpty()) {
            for (FileVO fileVo : fileList) {
                List<FileType> fileTypeList = fileVo.getFileTypeList();
                if (!fileTypeList.isEmpty()) {
                    for (FileType fileType : fileTypeList) {
                        List<String> list = fileType.getFileList();
                        fileType.setType(fileVo.getType());
                        CommonResult commonResult = addFile(list, fileType, id);
                        if (ShiroResultEnum.FAIL.getCode() == commonResult.getData()) {
                            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "附件保存失败");
                        }
                    }
                }
            }
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    public CommonResult addFile(List<String> list, FileType fileType, String id) {
        if (!list.isEmpty()) {
            for (String path : list) {
                //保存到数据库
                int num = insertIntoArcUpload(id, null, path, fileType.getType(), fileType.getFileType());
                if (num == NumberEnum.ZERO.getNum()) {
                    return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "附件保存失败");
                }
            }
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    public CommonResult addFile(List<String> list, FileType fileType, String id, String busiNo) {
        if (!list.isEmpty()) {
            for (String path : list) {
                //保存到数据库
                int num = insertIntoArcUpload(id, busiNo, path, fileType.getType(), fileType.getFileType());
                if (num == NumberEnum.ZERO.getNum()) {
                    return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "附件保存失败");
                }
            }
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    /**
     * 保存到数据库
     *
     * @param reqNo    业务编号
     * @param path     图片路径
     * @param arcType  文件大类
     * @param fileType 文件类型
     * @return 新增结果
     */
    public int insertIntoArcUpload(String reqNo, String busiNo, String path, String arcType, String fileType) {
        //保存到数据库
        FileUpload fileUpload = new FileUpload();
        fileUpload.setArcType(arcType);
        fileUpload.setFileType(fileType);
        fileUpload.setCreater(ShiroUserUtil.getUserName());
        String uuid = UUIDUtil.getUUID();
        fileUpload.setId(uuid);
        fileUpload.setReqNo(reqNo);
        fileUpload.setBusiNo(busiNo);
        fileUpload.setFilePath(path);
        return fileMapper.insert(fileUpload);
    }

    /**
     * 修改附件集合
     *
     * @param fileList 附件集合
     * @param id       业务ID
     */
    public CommonResult updateFile(List<FileVO> fileList, String id) {
        return updateFile(fileList, id, null);
    }

    public CommonResult updateFile(List<FileVO> fileList, String id, String busiNo) {
        if (fileList != null && !fileList.isEmpty()) {
            for (FileVO fileVo : fileList) {
                List<FileType> fileTypeList = fileVo.getFileTypeList();
                if (!fileTypeList.isEmpty()) {
                    for (FileType fileType : fileTypeList) {
                        //修改后的图片路径集合
                        List<String> list = fileType.getFileList();
                        //修改前的图片路径集合
                        List<String> oldPathList = getFilePathListByFileUpload(id, busiNo, fileVo.getType(), fileType.getFileType());
                        //查询两个集合的交集
                        List<String> intersection = list.stream().filter(item -> oldPathList.contains(item)).collect(Collectors.toList());
                        //取出各自集合中的差集，将修改后的路径加入数据库，将修改前的差集删掉
                        list.removeAll(intersection);
                        oldPathList.removeAll(intersection);
                        fileType.setType(fileVo.getType());
                        CommonResult commonResult = addFile(list, fileType, id, busiNo);
                        if (ShiroResultEnum.FAIL.getCode() == commonResult.getData()) {
                            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), commonResult.getMessage());
                        }
                        //处理修改前的数据
                        CommonResult result = dealOldPathList(oldPathList);
                        if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
                            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), result.getMessage());
                        }
                    }
                }
            }
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    /**
     * 变更图档
     *
     * @param fileList    图档集合
     * @param id          业务ID
     * @param modifyType  变更类型
     * @param modifyCause 变更原因
     * @param id          变更的ID
     * @return 操作结果
     */
    public int modifyFile(List<FileVO> fileList, String id, String modifyType, String modifyCause, String uuid) {
        int total = 0;
        if (fileList != null && !fileList.isEmpty()) {
            for (FileVO fileVo : fileList) {
                List<FileType> fileTypeList = fileVo.getFileTypeList();
                if (!fileTypeList.isEmpty()) {
                    for (FileType fileType : fileTypeList) {
                        //修改后的图片路径集合
                        List<String> list = fileType.getFileList();
                        //修改前的图片路径集合
                        List<String> oldPathList = getFilePathListByFileUpload(id, null, fileVo.getType(), fileType.getFileType());
                        //查询两个集合的交集
                        List<String> intersection = list.stream().filter(item -> oldPathList.contains(item)).collect(Collectors.toList());
                        //取出各自集合中的差集，将修改后的路径加入数据库，将修改前的差集删掉
                        list.removeAll(intersection);
                        oldPathList.removeAll(intersection);
                        fileType.setType(fileVo.getType());
                        //处理数据
                        int num = dealList(oldPathList, list, id, modifyType, modifyCause, uuid, fileType);
                        total += num;
                    }
                }
            }
        }
        return total;
    }

    /**
     * 处理变更
     *
     * @param oldPathList 原始数据
     * @param list        新数据
     * @param businessId  业务ID
     * @param modifyType  变更类型
     * @param modifyCause 变更原因
     * @param uuid        变更ID(base_modify_req表的ID)
     */
    private int dealList(List<String> oldPathList, List<String> list, String businessId, String modifyType, String modifyCause, String uuid, FileType fileType) {
        if (!oldPathList.isEmpty() || !list.isEmpty()) {
            //base_modify_detail表中增加一条数据
            String id = UUIDUtil.getUUID();
            int num = addModifyDetail(id, uuid, fileType.getName());
            if (num == 0) {
                return num;
            }
            //查询base_modify_req表中是否存在变更记录，不存在，则新增一条
            int count = baseModifyReqMapper.selectCountId(uuid);
            if (count == 0) {
                int i = modifyUtil.saveModifyReq(uuid, businessId, modifyType, modifyCause, ShiroUserUtil.getUserName());
                if (i == 0) {
                    return i;
                }
            }
            //base_modify_file_detail表中增加变更的图档信息
            int j = addFileDetailPath(oldPathList, list, fileType, id, null);
            if (j == 0) {
                return j;
            }
            return NumberEnum.ONE.getNum();
        }
        return NumberEnum.ZERO.getNum();
    }

    public int addFileDetailPath(List<String> oldPathList, List<String> list, FileType fileType, String id, String creater) {
        //base_modify_file_detail表中增加变更的图档信息
        for (String path : oldPathList) {
            int i = addFileDetail(id, path, NumStrEnum.ONE.getNum(), fileType, creater);
            if (i == 0) {
                return i;
            }
        }
        for (String path : list) {
            int i = addFileDetail(id, path, NumStrEnum.TWO.getNum(), fileType, creater);
            if (i == 0) {
                return i;
            }
        }
        return 1;
    }

    /**
     * base_modify_detail表中增加一条数据
     *
     * @param id   base_modify_detail的Id
     * @param uuid base_modify_req的ID
     * @param name 变更项中文名
     * @return 新增结果
     */
    public int addModifyDetail(String id, String uuid, String name) {
        BaseModifyDetail baseModifyDetail = new BaseModifyDetail();
        baseModifyDetail.setId(id);
        baseModifyDetail.setReqNo(uuid);
        baseModifyDetail.setName(name);
        baseModifyDetail.setColumnName(name);
        baseModifyDetail.setType(NumStrEnum.THREE.getNum());
        baseModifyDetail.setOldValue("图档详情");
        baseModifyDetail.setNewValue("图档详情");
        baseModifyDetail.setCreater(ShiroUserUtil.getUser().getOperName());
        return baseModifyDetailMapper.insert(baseModifyDetail);
    }

    /**
     * 新增图档变更
     *
     * @param id   base_modify_detail表的ID
     * @param path 图片路径
     * @param type 图档类型
     * @return 新增结果
     */
    public int addFileDetail(String id, String path, String type, FileType fileType, String creater) {
        BaseModifyFileDetail baseModifyFileDetail = new BaseModifyFileDetail();
        baseModifyFileDetail.setModifyDetailId(id);
        baseModifyFileDetail.setType(type);
        baseModifyFileDetail.setArcType(fileType.getType());
        baseModifyFileDetail.setFileType(fileType.getFileType());
        baseModifyFileDetail.setFilePath(path);
        baseModifyFileDetail.setCreater(StringUtils.isNotBlank(creater) ? creater : ShiroUserUtil.getUser().getOperName());
        baseModifyFileDetail.setId(UUIDUtil.getUUID());
        return fileMapper.insertFileDetail(baseModifyFileDetail);
    }

    /**
     * 处理修改前的数据
     *
     * @param oldPathList 修改前的数据
     */
    private CommonResult dealOldPathList(List<String> oldPathList) {
        if (oldPathList != null && !oldPathList.isEmpty()) {
            String filePath = String.join(",", oldPathList);
            int num = fileMapper.deletePath(filePath);
            if (num == 0) {
                return CommonResult.ResponseResult(num, "删除图片失败");
            }
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    /**
     * 通过文件类型查询文件
     *
     * @param fileUpload 查询实体
     * @return 文件信息
     */
    @Override
    public List<FileUpload> getFileList(FileUpload fileUpload) {
        //如果是业主的附件查询，查看当前业主是否为附房业主，如果是附房业主，则查询住房的业主图档
        if (FileTypeEnum.OWNER_INFO_FILE.getType().equals(fileUpload.getArcType())) {
            //查询业主表中的主房业主ID（owner_id）（附房有主房的业主ID，主房中，该字段为空）
            String ownerId = fileMapper.getOwnerId(fileUpload.getBusinessId());
            if (StringUtils.isNotBlank(ownerId)) {
                fileUpload.setBusinessId(ownerId);
            }
        }
        return fileMapper.getList(fileUpload);
    }

    /**
     * 查询图片路径集合
     *
     * @param fileUpload 查询实体
     * @return 图片路径集合
     */
    public List<String> getFilePathList(FileUpload fileUpload) {
        //如果是业主的附件查询，查看当前业主是否为附房业主，如果是附房业主，则查询住房的业主图档
        if (FileTypeEnum.OWNER_INFO_FILE.getType().equals(fileUpload.getArcType())) {
            //查询业主表中的主房业主ID（owner_id）（附房有主房的业主ID，主房中，该字段为空）
            String ownerId = fileMapper.getOwnerId(fileUpload.getReqNo());
            if (StringUtils.isNotBlank(ownerId)) {
                fileUpload.setReqNo(ownerId);
            }
        }
        return fileMapper.getPathList(fileUpload);
    }

    /**
     * 变更审核通过后，处理图片逻辑
     *
     * @param id    变更ID
     * @param reqNo 业务ID
     * @return 处理结果
     */
    public CommonResult dealPassModifyFile(String id, String reqNo) {
        //查询删除的图档路径集合
        List<String> filePathList = fileMapper.getDelFilePath(id);
        if (filePathList != null && !filePathList.isEmpty()) {
            String filePath = String.join(",", filePathList);
            int num = fileMapper.deletePath(filePath);
            if (num == 0) {
                return CommonResult.ResponseResult(num, "变更审核通过后，删除图片失败");
            }
        }
        //查询新增的图档集合
        List<BaseModifyFileDetail> list = fileMapper.getModifyFileList(id);
        if (list != null && !list.isEmpty()) {
            for (BaseModifyFileDetail baseModifyFileDetail : list) {
                int num = insertIntoArcUpload(reqNo, null, baseModifyFileDetail.getFilePath(), baseModifyFileDetail.getArcType(), baseModifyFileDetail.getFileType());
                if (num == NumberEnum.ZERO.getNum()) {
                    return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "变更审核通过后，附件新增失败");
                }
            }
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    /**
     * 获取业务ID的文件类型以及数量
     *
     * @param id      业务id
     * @param arcType 附件大类(以逗号分隔)
     * @return 文件类型和数量
     */
    @Override
    public List<FileType> getFileType(String id, String arcType) {
        List<FileType> list = new ArrayList<>();
        List<String> typeList = Arrays.asList(arcType.split(","));
        if (!typeList.isEmpty()) {
            for (String type : typeList) {
                //查询每个大类文件类型和数量
                list = fileMapper.getFileType(id, type, null);
                dealTypeList(list, id, type, null);
            }
        }
        return list;
    }

    /**
     * 校验图档上传的必传项
     *
     * @param businessId 业务ID
     * @param type       图档类型（用逗号分隔）
     * @return 校验结果
     */
    @Override
    public CommonResult checkFile(String businessId, String type) {
        /**
         * 查询图档类型的必传项的数量
         */
        List<FileType> list = fileMapper.checkFile(businessId, type);
        if (list == null || list.size() == 0) {
            return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
        }
        StringBuilder str = new StringBuilder(6);
        //校验必传项的数量，如果为0，则表示该类型未上传图档
        for (FileType file : list) {
            if (file.getNum() == 0) {
                str.append(",").append(file.getName());
            }
        }
        if (str.length() > 0) {
            str.deleteCharAt(0);
            str.append(":未上传图档");
            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), str.toString());
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    /**
     * 获取业务ID的文件类型已经数量
     *
     * @param id      业务id
     * @param arcType 附件大类(以逗号分隔)
     * @return 文件类型和数量
     */
    @Override
    public List<FileVO> getFileVOList(String id, String arcType) {
        return getFileVOList(id, arcType, null);
    }

    @Override
    public List<FileVO> getFileVOList(String id, String arcType, String busiNo) {
        List<FileVO> list = new ArrayList<>();
        if (StringUtils.isNotBlank(arcType)) {
            List<String> arcTypeList = Arrays.asList(arcType.split(","));
            if (!arcTypeList.isEmpty()) {
                for (String type : arcTypeList) {
                    FileVO fileVO = fileMapper.getFileVO(type);
                    if (fileVO != null) {
                        //查询每个大类文件类型和数量
                        List<FileType> typeList = fileMapper.getFileType(id, type, busiNo);
                        dealTypeList(typeList, id, type, busiNo);
                        fileVO.setFileTypeList(typeList);
                        list.add(fileVO);
                    }
                }
            }
        }
        return list;
    }

    private void dealTypeList(List<FileType> typeList, String id, String type, String busiNo) {
        if (!typeList.isEmpty()) {
            for (FileType f : typeList) {
                FileUpload fileUpload = new FileUpload();
                fileUpload.setReqNo(id);
                fileUpload.setArcType(type);
                fileUpload.setFileType(f.getFileType());
                List<String> fileList = getFilePathListByFileUpload(id, busiNo, type, f.getFileType());
                f.setFileList(fileList);
            }
        }
    }

    /**
     * 获取图片路径
     *
     * @param id       业务ID
     * @param type     大类
     * @param fileType 小类
     * @return 路径集合
     */
    @Override
    public List<String> getFilePathListByFileUpload(String id, String busiNo, String type, String fileType) {
        FileUpload fileUpload = new FileUpload();
        fileUpload.setReqNo(id);
        fileUpload.setArcType(type);
        fileUpload.setFileType(fileType);
        fileUpload.setBusiNo(busiNo);
        return getFilePathList(fileUpload);
    }

    /*@Override
    public List<BaseOwnerInfo> getBusiFileList(String busiNo, String arcType) {
        // 根据busiNo查询业主列表
        // 根据业主列表，查询所有图档资料
        // 根据业主、附件类型、文件类型对图档进行分类
        List<BaseOwnerInfo> rList = new ArrayList<>();
        Map<String, Map<String, Map<String, FileType>>> map = new HashMap<>();
        Map<String, Map<String, FileType>> actTypeMap = null;
        Map<String, FileType> fileTypeMap = null;
        FileType fileType = null;
        List<AccTransactionLog> logList = accTransactionLogService.selectLogByBusiNo(busiNo);
        if (null != logList && !logList.isEmpty()) {
            List<String> ownerIds = new ArrayList<>();
            for (AccTransactionLog log : logList) {
                ownerIds.add(log.getOwnerId());
            }
            List<FileUpload> uploadList = fileMapper.getFileList(ownerIds);
            if (null != uploadList && !uploadList.isEmpty()) {
                for (FileUpload upload : uploadList) {
                    if (null == map.get(upload.getReqNo())) {
                        map.put(upload.getReqNo(), new HashMap<>());
                    }
                    actTypeMap = map.get(upload.getReqNo());
                    if (null == actTypeMap.get(upload.getArcType()+';'+upload.getArcTypeName())) {
                        actTypeMap.put(upload.getArcType()+';'+upload.getArcTypeName(), new HashMap<>());
                    }
                    fileTypeMap = actTypeMap.get(upload.getArcType()+';'+upload.getArcTypeName());
                    if (null == fileTypeMap.get(upload.getFileType()+';'+upload.getFileName())) {
                        fileTypeMap.put(upload.getFileType()+';'+upload.getFileName(), new FileType());
                    }
                    fileType = fileTypeMap.get(upload.getFileType()+';'+upload.getFileName());
                    fileType.setFileType(upload.getFileType());
                    fileType.setName(upload.getFileName());
                    fileType.getFileList().add(upload.getFilePath());
                }
            }
        }
        BaseOwnerInfo ownerInfo = null;
        String[] actTypeArr;
        for (String owner : map.keySet()) {
            ownerInfo = new BaseOwnerInfo();
            ownerInfo.setOwnerId(owner);
            ownerInfo.setName(owner);

            actTypeMap = map.get(owner);
            for (String actType : actTypeMap.keySet()) {
                FileVO fileVO = new FileVO();
                actTypeArr = actType.split(";");
                fileVO.setName(actTypeArr[0]);
                fileVO.setType(actTypeArr[1]);
                if (null == ownerInfo.getFileTypeList()) {
                    ownerInfo.setFileTypeList(new ArrayList<>());
                }
                ownerInfo.getFileTypeList().add(fileVO);

                fileTypeMap = actTypeMap.get(actType);
                for (String fType : fileTypeMap.keySet()) {
                    fileType = fileTypeMap.get(fType);
                    if (null == fileVO.getFileTypeList()) {
                        fileVO.setFileTypeList(new ArrayList<>());
                    }
                    fileVO.getFileTypeList().add(fileType);
                }
            }
            rList.add(ownerInfo);
        }
        return rList;
    }*/

    @Override
    public List<BaseOwnerInfo> getBusiFileList(String busiNo, String arcType) {
        // 根据busiNo查询业主列表
        // 根据业主列表，查询所有图档资料
        // 根据业主、附件类型、文件类型对图档进行分类
        List<BaseOwnerInfo> rList = new ArrayList<>();
        BaseOwnerInfo ownerInfo = null;
        List<AccTransactionLog> logList = accTransactionLogService.selectLogByBusiNo(busiNo);
        if (null != logList && !logList.isEmpty()) {
            for (AccTransactionLog log : logList) {
                ownerInfo = new BaseOwnerInfo();
                ownerInfo.setOwnerId(log.getOwnerId());
                ownerInfo.setName(log.getOwnerName());
                ownerInfo.setFileTypeList(this.getFileVOList(log.getOwnerId(), arcType, busiNo));
                rList.add(ownerInfo);
            }
        }

        return rList;
    }

    /**
     * 上传文件的方法
     *
     * @param file：文件的字节
     * @param imgPath：文件的路径
     * @param imgName：文件的名字
     * @throws Exception
     */
    public void uploadFileUtil(MultipartFile file, String imgPath, String imgName) throws Exception {
        FileOutputStream out = null;
        try {
            File targetFile = new File(imgPath);
            out = new FileOutputStream(imgPath + "/" + imgName);
            byte[] bytes;
            if (new ImageCheck().isImage(targetFile)) {
                bytes = compressPic(file.getBytes(), 0.1f);
            } else {
                bytes = file.getBytes();
            }
            out.write(bytes);
            out.flush();
        } finally {
            try {
                InputStream in = file.getInputStream();
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("IOException错误信息:()", e.getMessage(), e);
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("IOException错误信息:()", e.getMessage(), e);
                }
            }
        }

    }

    /**
     * @param path 需要遍历的路径
     * @return 路径下文件的名称集合
     */
    private static ArrayList<String> getFile(String path) {
        // 获得指定文件对象
        File file = new File(path);
        // 获得该文件夹内的所有文件
        File[] array = file.listFiles();
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < array.length; i++) {
            //如果是文件
            if (array[i].isFile()) {
                // 只输出文件名字
                list.add(array[i].getName());
            }
        }
        return list;
    }

    /**
     * @param names 文件下文件名的集合
     * @param name  存入的文件名
     * @param index 索引的开始位置
     * @return 符合要求的文件名
     */
    private static String checkFileName(ArrayList<String> names, String name, int index) {
        if (names.contains(name)) {
            if (names.contains(name.substring(NumberEnum.ZERO.getNum(), name.indexOf(POINT)) + index + name.substring(name.indexOf(POINT), name.length()))) {
                name = checkFileName(names, name, index + NumberEnum.ONE.getNum());
            } else {
                return name.substring(NumberEnum.ZERO.getNum(), name.indexOf(POINT)) + index + name.substring(name.indexOf(POINT), name.length());
            }
        }
        return name;
    }

    /**
     * 等分辨率压缩
     *
     * @param imageByte 文件字节
     * @param quality   缩放比例
     * @return
     */
    public static byte[] compressPic(byte[] imageByte, float quality) {
        byte[] inByte = null;
        try {
            ByteArrayInputStream byteInput = new ByteArrayInputStream(imageByte);
            Image img = ImageIO.read(byteInput);
            float newWidth = img.getWidth(null);
            float newHeight = img.getHeight(null);
            Image image = img.getScaledInstance((int) newWidth, (int) newHeight, Image.SCALE_SMOOTH);
            // 缩放图像
            BufferedImage tag = new BufferedImage((int) newWidth,
                    (int) newHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = tag.createGraphics();
            // 绘制缩小后的图
            g.drawImage(image, 0, 0, null);
            g.dispose();
            ByteArrayOutputStream out = new ByteArrayOutputStream(imageByte.length);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
            /* 压缩质量 */
            jep.setQuality(quality, true);
            encoder.encode(tag, jep);
            inByte = out.toByteArray();
            out.close();

        } catch (IOException ex) {
            log.error("IOException错误信息:()", ex.getMessage(), ex);
        }
        return inByte;
    }

    /**
     * 检验必填项
     *
     * @param fileList 附件集合
     * @return 检验结果
     */
    public CommonResult checkFileList(List<FileVO> fileList) {
        for (FileVO fileVO : fileList) {
            List<FileType> fileTypeList = fileVO.getFileTypeList();
            for (FileType fileType : fileTypeList) {
                String mandatory = fileType.getMandatory();
                if (NumStrEnum.ONE.getNum().equals(mandatory)) {
                    List<String> list = fileType.getFileList();
                    if (list.size() < 0) {
                        return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), fileType.getName() + ":未上传图片");
                    }
                }
            }
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    /**
     * 获取变更的图档详情
     *
     * @param modifyDetailId 变更项ID
     * @return 变更图档详情
     */
    @Override
    public FileDetailList getModifyFileDetail(String modifyDetailId) {
        FileDetailList fileDetailList = new FileDetailList();
        //原始数据集合
        List<BaseModifyFileDetail> oldFileList = fileMapper.getFileDetailList(modifyDetailId, NumStrEnum.ONE.getNum());
        fileDetailList.setOldFileList(oldFileList);
        //新数据集合
        List<BaseModifyFileDetail> newFileList = fileMapper.getFileDetailList(modifyDetailId, NumStrEnum.TWO.getNum());
        fileDetailList.setNewFileList(newFileList);
        return fileDetailList;
    }

    /**
     * 上传附件保存到数据库
     *
     * @param list 附件集合
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult saveFile(List<FileForDialog> list) {
        if (list != null && !list.isEmpty()) {
            for (FileForDialog fileForDialog : list) {
                List<FileVO> fileTypeList = fileForDialog.getFileTypeList();
                CommonResult result = updateFile(fileTypeList, fileForDialog.getId(), fileForDialog.getBusiNo());
                if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "附件保存失败");
                }
            }
        }
        return CommonResult.ResponseResult(1);
    }

    /**
     * 删除图档大类下的图片
     *
     * @param id      业务ID
     * @param arcType 图档大类
     * @return 删除结果
     */
    public int deleteByArcType(String id, String arcType) {
        //查询当前Id业务下的图档大类的所有文件ID集合（以逗号分隔）
        String delFileId = fileMapper.getDelFileId(id, arcType);
        if (delFileId != null && delFileId.length() > 0) {
            int num = fileMapper.deleteByIds(delFileId);
            if (num <= 0) {
                return 0;
            }
        }
        return 1;
    }

}
